package kz.alamty.dev.interceptor;


import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;



import kz.alamty.dev.service.LoginManager;
import kz.alamty.dev.util.TheConstant;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ValidationAware;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class LoginIntercepter implements Interceptor {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private LoginManager loginMa; 


	public void setLoginMa(LoginManager loginMa) {
		System.out.println("****** setLoginMa() method called");
		this.loginMa = loginMa;
	}
	public LoginIntercepter() {
		System.out.println("****** LoginIntercepter() method called");
	}

	@Override
	public void destroy() {
		System.out.println("****** destroy() method called");
	}
 
	@Override
	public void init() {
		System.out.println("****** init() method called");
	}

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		System.out.println("****** intercept() method called");
	    final ActionContext context = invocation.getInvocationContext ();
	    HttpServletRequest request = (HttpServletRequest) context.get(ServletActionContext.HTTP_REQUEST);
	    HttpSession session =  request.getSession (true);
	    
	    Object user = session.getAttribute (TheConstant.LOGIN_USER);
	    
	    if (user == null) {

	        String loginName = request.getParameter (TheConstant.LOGIN_NAME);
	        if (! StringUtils.isBlank (loginName) ) { 

	            if (processLogin (request, session) ) {
	                return "login";
	            } else {
	                Object action = invocation.getAction ();
	                if (action instanceof ValidationAware) {
	                    ((ValidationAware) action).addActionError ("Username or password incorrect");
	                }
	            }
	        }

	        return "login";
	    } else {
	        return invocation.invoke ();
	    }
	    
	}

	/**
	 * 
	 * @param request
	 * @param session
	 * @return
	 */
	private boolean processLogin(HttpServletRequest request, HttpSession session) {
	    String username = request.getParameter (TheConstant.LOGIN_NAME);
	    String password = request.getParameter (TheConstant.LOGIN_PASSWORD);

	    Object user = loginMa.login (username, password);

	    if (user != null) {
	        session.setAttribute (TheConstant.LOGIN_USER, user);
	        return true;
	    } else {
	        return false;
	    }
	}
	
	

}
